#!/bin/bash -eu

readonly INPUT_PARAMS="$*"

if [ "${INPUT_PARAMS}" = 'qinit' ]
then
  if [ ! -f ~/.qgit ]
  then
    printf "# qgit config\n\n# Lines starting with '#' will be considered invalid\n\n# <remote-name1>\n# <remote-name2>\n" > ~/.qgit
  fi
  exit 0
fi

if [ "${INPUT_PARAMS}" = '' ] || [[ "${INPUT_PARAMS}" =~ ^(--qhelp|-qh|qhelp)($|[\ ]+.+) ]]
then
  cat << EOF | sed 's/^ \{6\}//g'
      usage: qgit [--qhelp] [-qh] [help]
                  <git-command> [<args>]

      You can run the 'qgit' to get the help information, or you can also use other commands or options.

      These are common qgit commands used in various situations:
      notes: the 'q' stands for the abbreviation of qgit, just to distinguish it from the commands of git itself

             -qh            ↓
             --qhelp        ↓
             qhelp          Get usage and help information of qgit
             qinit          Generate a configuration file in which you need to add all the remote names you want to use
                            notes: if the configuration file already exists, this command will not do anything;
                                   otherwise, it will generate a new configuration file and put into some comment information

      Using git subcommands, when multiple remotes are involved, the qgit will execute the same git operation on each remote in turn
      notes: when the executed git subcommand involves the remote name, you can use '-' instead. When it's actually executed, '-' will be replaced with the real remote name

      Example:
        【qgit push - master】 equals 【git push <remote1> master && git push <remote2> master】
EOF
  exit 0
fi

if [[ "${INPUT_PARAMS}" =~ ( - |\ -$|^- |^-$) ]]
then
  while read -r side
  do
    if [[ ! "${side}" =~ (^\#|^$) ]]
    then
      echo "Execute git operation on $side ......"

      if [ "${INPUT_PARAMS}" = '-' ]
      then
        generated_command=${side}
      else
        generated_command=${INPUT_PARAMS/#- /$side }
        generated_command=${generated_command// - / $side }
        generated_command=${generated_command//\ -\//\ $side\/}
        generated_command=${generated_command/% -/ $side}
      fi

      eval "git ${generated_command}"

      echo
    fi
  done < ~/.qgit
else
  eval "git ${INPUT_PARAMS}"
fi
